import { computed,toRefs } from "vue"
import { useStore } from "vuex"

export const useCommomCartEffect = (shopId) => {
    const store = useStore();
    // const cartList = toRefs(store.state);
    const cartList = store.state.cartList
    const changeCartItemInfo = (shopId, productId, productInfo, num) => {
        store.commit('changeCartItemInfo',{
            shopId, productId, productInfo, num
        })
    };
    console.log("cartList:",cartList)
    //点击购物车弹框内的数据
    const productList = computed( ()=>{
        // console.log("vxcartList[]:",cartList);
        // console.log(cartList[1]);
        const productList = cartList[shopId] || {};
        // console.log('mproductList',productList);
        const notEmptyList = {};
        for( let i in productList ){
            const product = productList[i]
            // console.log("product:::",product);
            product.sumPrice = product.count * product.price;
            // console.log(product.sumPrice);
            notEmptyList[i] = product;
        }
        let Aprice = 0;
        let sumPrice = 0;
        for( let i in productList ){
            // console.log(notEmptyList[i].sumPrice);
            Aprice+=notEmptyList[i].sumPrice;
            sumPrice+=notEmptyList[i].sumPrice;
        }
        // console.log("Aprice:",Aprice);
        // notEmptyList[Aprice] = Aprice;
        notEmptyList.sumPrice = Aprice;
        // console.log("notEmptyList:",notEmptyList);
        store.commit('changeTotalPrice',{
            shopId,sumPrice,Aprice
        })
        return notEmptyList;
    })

    const shopName = computed( ()=>{
        // 如果此处仅做取值而不使用计算属性，会导致如果shopId变化时，获取不到shopName
        const shopName = cartList[shopId]?.shopName || ''
        return shopName
    });

    // 计算总价格s
    const caculations = computed ( ()=>{
        // 1、获取商品列表
        const productList =  cartList[shopId] || {};
        // console.log("vxProductList：",productList);
        const result = {total: 0, price: 0, allChecked: true}
        // 2、计算每个商品的价格
        if(productList){
            for(let i in productList){
                // console.log(productList[i]);
                const product = productList[i];
                result.total += product.count;//计算总数
                if(product.check){
                    result.price += (product.price * product.count);
                }
                if(product.count > 0 && !product.check){
                    result.allChecked = false;
                }
            }
        }
        result.price = result.price.toFixed(2);
        return result
    });
    return { cartList, productList, shopName, changeCartItemInfo, caculations }
}